package com.xm.permission;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

/**
 * 权限辅助类，用于提供给uni-app调用自启动权限相关功能
 */
public class PermissionHelper {
    private static final String TAG = "PermissionHelper";
    
    private static PermissionCallback mResultCallback;
    
    /**
     * 设置权限结果回调
     */
    public static void setResultCallback(PermissionCallback callback) {
        mResultCallback = callback;
    }
    
    /**
     * 检查并请求自启动权限
     */
    public static void checkAndRequestAutoStartPermission(Activity activity, PermissionCallback callback) {
        setResultCallback(callback);
        
        // 检查无障碍服务
        if (!isAccessibilitySettingsOn(activity)) {
            openAccessibilitySettings(activity);
            return;
        }
        
        // 请求自启动权限
        AutoStartHelper.getInstance().getAutoStartPermission(activity);
    }
    
    /**
     * 通知结果给uni-app
     */
    public static void notifyResult(boolean success,String tips) {
        if (mResultCallback != null) {
            Log.i(TAG, "通知uni-app自启动权限结果: " + success);
            mResultCallback.onResult(success,tips);
            // 回调完成后清除引用
            mResultCallback = null;
        } else {
            Log.w(TAG, "未设置回调，无法通知结果");
        }
    }
    
    /**
     * 检查无障碍服务是否开启
     */
    public static boolean isAccessibilitySettingsOn(Context context) {
        int accessibilityEnabled = 0;
        try {
            accessibilityEnabled = Settings.Secure.getInt(
                    context.getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
            Log.e(TAG, "获取无障碍设置失败", e);
        }

        if (accessibilityEnabled == 1) {
            String services = Settings.Secure.getString(
                    context.getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            
            if (services != null) {
                return services.toLowerCase().contains(context.getPackageName().toLowerCase());
            }
        }
        return false;
    }
    
    /**
     * 打开无障碍设置页面
     */
    public static void openAccessibilitySettings(Context context) {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
} 